import { createRouter } from '@gowiny/uni-router';
import type { BeforeEachResult } from '@gowiny/uni-router';
import PAGE_DATA from '@/pages.json';
// import { getWeChatCode, weChatHideMenu } from '@/assets/js/wechat';
import { setStorage, getStorage, delStorage, isWeChat, loadScript, isEmpty } from '@/assets/js/utils';
import { login } from '@/api/login';
import { addUserSystemInfo } from '@/api/common';

//映射路由
const router = createRouter({
    pageData: PAGE_DATA
});

//前置路由守卫
router.beforeEach((to: any, from) => {
    return new Promise<BeforeEachResult>(async (success, fail) => {
        // setStorage('token', 'eyJhbGciOiJIUzI1NiJ9.eyJtaW5pVmVyc2lvbiI6Miwic3ViIjoiMzU3NzQ3NTE1OTA4NTU0NzUyIiwib3BlbmlkIjoib3N4MzM2M2poYnpwbEdoZU1kMHBLMTFFQkVLdyIsImV4cCI6MTc0NjczMzE5OSwidXNlcklkIjozNTc3NDc1MTU5MDg1NTQ3NTIsImlhdCI6MTc0NjcxMTU4OSwianRpIjoiMWM2NWY5MmQtZGI5Mi00MmUxLTg4YmMtMzg4NzJiZGNlNTViIn0.eD4bv7GWScVSFEBzKDClHzjY9U1wu76AC863ZcZkSG0');
        let token = getStorage('token');
        //本地没有openId缓存进行登录操作
        if (isEmpty(token)) {
            // #ifdef MP-WEIXIN
            uni.login({
                provider: 'weixin',
                success: async res => {
                    if (res && res.code) {
                        let [result, err] = await login(res.code);
                        setStorage('token', result);
                        // 保存用户系统信息
                        try {
                            let systemInfo = uni.getSystemInfoSync();
                            addUserSystemInfo({
                                appVersion: systemInfo.appVersion,
                                osName: systemInfo.osName,
                                uniPlatform: systemInfo.uniPlatform
                            });
                        } catch (error) { }
                        success(true);
                    }
                },
                fail: err => {
                    console.log(err);
                }
            });
            // #endif
            // #ifndef MP-WEIXIN
            success(true);
            // #endif
        } else {
            success(true);
        }
    });
});

//后置路由守卫
router.afterEach((to, from) => {
    return new Promise<BeforeEachResult>(async (success, fail) => {
        //后置路由隐藏微信菜单（weChatHideMenu()不加await防止阻塞页面）
        // weChatHideMenu();
        success(true);
    });
});

export default router;
